package com.oj.timer;

import com.oj.entity.OnlineUser;
import com.oj.entity.User;
import com.oj.service.UserService;
import com.oj.util.OnlineUserUtil;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.util.*;

@Slf4j
@Component
public class OnlineUserSchedule {
    @Autowired
    private UserService userService;

    @Scheduled(fixedDelay = 30*60*1000)
    private void onlineUserTimer() {
        try {
            Map<String, OnlineUser> mou = new HashMap<String, OnlineUser>();
            mou = OnlineUserUtil.getOnlineUsers();
            Set set = mou.keySet();
            Iterator it=set.iterator();
            while(it.hasNext()){
                String username = (String) it.next();
                if(username==null){
                    it.remove();
                    continue;
                }

                User u = userService.query(username);
                if(u == null){
                    it.remove();
                    continue;
                }

                long time_now = new Date().getTime();
                long time_cache = mou.get(username).getLastAccessTime().getTime();
                if ((time_now - time_cache) > 60 * 30 * 1000){
                    log.info(username + " remove from online list, because of no action last 30 mins");
                    it.remove();
                    continue;
                }

                u.setLastaccesstime(mou.get(username).getLastAccessTime());
                userService.update(u);

                if (mou.get(username).getOnline() == 0){
                    log.info(username + " remove from online list, because of offline.");
                    it.remove();
                    continue;
                }
            }
        }catch (Exception e) {
        }
    }
}
